package br.com.passeionaweb.android.TabelaFipe.db;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.test.IsolatedContext;

public class PricesDatabaseHelper extends SQLiteOpenHelper {

	private static int DATABASE_VERSION = 1;
	private static final String DATABASE_NAME = "pricescache";
	private static final String TABLE_NAME = "Prices";
	public static final String KEY_ID = "_id";
	public static final String KEY_MAKE = "make";
	public static final String KEY_MODEL = "model";
	public static final String KEY_YEAR = "year";
	public static final String KEY_VERSION = "version";
	public static final String KEY_PRICE = "price";
	public static final String KEY_TIMESTAMP = "timestamp";
	private static final String CREATE_SQL = "create table " + TABLE_NAME + " ("
			+ KEY_ID + " integer primary key autoincrement ," + KEY_MAKE + " text ," + KEY_MODEL
			+ " text ," + KEY_YEAR + " text ," + KEY_VERSION + " text ," + KEY_PRICE + " text ,"
			+ KEY_TIMESTAMP + " datetime )";

	private SQLiteDatabase db;
	
	public PricesDatabaseHelper(Context context) {
		super(context, DATABASE_NAME, null, DATABASE_VERSION);
	}

	@Override
	public void onCreate(SQLiteDatabase db) {
		System.out.println(CREATE_SQL);
		try {
			db.execSQL(CREATE_SQL);
		}catch (SQLException e) {
			e.printStackTrace();
		}
	}

	@Override
	public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
		// TODO Auto-generated method stub
	}

	public Cursor getAllPrices() {
		db = getWritableDatabase();
		try {
			return db.query(TABLE_NAME, new String[] { KEY_ID, KEY_MAKE, KEY_MODEL, KEY_YEAR,
					KEY_VERSION, KEY_PRICE, KEY_TIMESTAMP }, null, null, null, null, KEY_TIMESTAMP
					+ " DESC");
		} finally {
			//db.close();
		}
	}

	public long insertPrice(String make, String model, String year, String version, String price) {
	    db = getWritableDatabase();
		try {
			ContentValues values = new ContentValues();
			values.put(KEY_MAKE, make);
			values.put(KEY_MODEL, model);
			values.put(KEY_VERSION, version);
			values.put(KEY_YEAR, year);
			values.put(KEY_PRICE, price);
			values.put(KEY_TIMESTAMP, System.currentTimeMillis());
			long result = db.insertOrThrow(TABLE_NAME, null, values);
			System.out.println(result);
			return result;
		} finally {
			db.close();
			close();
		}
	}

	public int deletePrice(long id) {
		db = getWritableDatabase();
		try {
			return db.delete(TABLE_NAME, KEY_ID + " = " + id, null);
		} finally {
			db.close();
		}
	}

	public int deleteAll() {
		db = getWritableDatabase();
		try {
			return db.delete(TABLE_NAME, "1", null);
		} finally {
			db.close();
		}
	}
}
